package Administration;

/**
 *
 * @author kazim
 */
import pojo.hibernate.Erpmusers;
import pojo.hibernate.ErpmusersDAO;
import pojo.hibernate.Departmentmaster;
import pojo.hibernate.ErpmItemMasterDAO;
import pojo.hibernate.Institutionmaster;
import pojo.hibernate.InstitutionmasterDAO;
import pojo.hibernate.Subinstitutionmaster;
import pojo.hibernate.SubinstitutionmasterDAO;
import pojo.hibernate.Institutionuserroles;
import pojo.hibernate.InstitutionuserroleDAO;
import pojo.hibernate.Erpmuserrole;
import pojo.hibernate.ErpmuserroleDAO;
import utils.sendMail;
import utils.DevelopmentSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import com.opensymphony.xwork2.ActionContext;


/**
 *
 * @author kazim
 */
public class ManageUserAction extends DevelopmentSupport {

    private Erpmusers erpmusers;
    private Erpmuserrole erpmur;
    private ErpmusersDAO erpmusersDao = new ErpmusersDAO();
    private List<Institutionmaster> imIdList = new ArrayList<Institutionmaster>();
    private List<Subinstitutionmaster> simImIdList = new ArrayList<Subinstitutionmaster>();
    private List<Departmentmaster> dmIdList = new ArrayList<Departmentmaster>();
    private List<Institutionuserroles> iurIdList = new ArrayList<Institutionuserroles>();
    private InstitutionmasterDAO imDao = new InstitutionmasterDAO();
    private List<Erpmuserrole> erpmurList = new ArrayList<Erpmuserrole>();
    
    private String message;
    private Integer erpmuId;
    private String erpmuName;    
    private String RetypedPassword;
    private Integer erpmurId;
    private String erpmusersdob;

    public void seterpmuId(Integer erpmuId) {
        this.erpmuId = erpmuId;
    }

    public Integer geterpmuId() {
        return this.erpmuId;
    }

    public Erpmusers geterpmusers() {
        return this.erpmusers;
    }

    public void seterpmusers(Erpmusers erpmusers) {
        this.erpmusers = erpmusers;
    }

    public void setimIdList(List<Institutionmaster> imIdList) {
        this.imIdList = imIdList;
    }

    public List<Institutionmaster> getimIdList() {
        return this.imIdList;
    }

    public void setsimImIdList(List<Subinstitutionmaster> simImIdList) {
        this.simImIdList = simImIdList;
    }

    public List<Subinstitutionmaster> getsimImIdList() {
        return this.simImIdList;
    }

    public void setdmIdListList(List<Departmentmaster> dmIdList) {
        this.dmIdList = dmIdList;
    }

    public List<Departmentmaster> getdmIdList() {
        return this.dmIdList;
    }

    public void setiurIdList(List<Institutionuserroles> iurIdList) {
        this.iurIdList = iurIdList;
    }

    public List<Institutionuserroles> getiurIdList() {
        return this.iurIdList;
    }


    public String geterpmusersdob() {
        return this.erpmusersdob;
    }

    public void geterpmusersdob(String erpmusersdob) {
        this.erpmusersdob = erpmusersdob;
    }

    public String getMessage() {
        return this.message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void seterpmuName(String erpmuName) {
        this.erpmuName = erpmuName;
    }

    public String geterpmuName() {
        return this.erpmuName;
    }


    public void setRetypedPassword(String RetypedPassword) {
        this.RetypedPassword = RetypedPassword;
    }

    public String getRetypedPassword() {
        return this.RetypedPassword;
    }

   public void seterpmurList(List<Erpmuserrole> erpmurList) {
        this.erpmurList = erpmurList;
    }

    public List<Erpmuserrole> geterpmurList() {
        return this.erpmurList;
    }

    public Erpmuserrole geterpmur() {
        return this.erpmur;
    }

    public void seterpmur(Erpmuserrole erpmur) {
        this.erpmur = erpmur;
    }

    public Integer geterpmurId() {
        return this.erpmurId;
    }

    public void seterpmurId(Integer erpmurId) {
        this.erpmurId = erpmurId;
    }
    
    @Override
    public String execute() throws Exception {
        try {           
            return SUCCESS;
        } catch (Exception e) {
            message = "Exception in -> RegisterUserAxn" + e.getMessage() + " Reported Cause is: " + e.getCause();
            return ERROR;
        }
    }

    public String Save() throws Exception {
        try {
            //If part saves record for the first time; else parts is for record update
            if (erpmusers.getErpmuId() == null) {
                erpmusers.setErpmuActive("N");
                erpmusersDao.save(erpmusers);

                //Prepare Lists for Setting up User Profile
                imIdList = imDao.findAll();

                //Set User Name for creating Prifile on the User Profile Creation Screen
                erpmuName = erpmusers.getErpmuName();
            } else {
                Erpmusers erpmusers2 = erpmusersDao.findByUserName(erpmusers.getErpmuName());
                erpmusers2 = erpmusers;
                erpmusersDao.update(erpmusers2);
            }

            return SUCCESS;
        } catch (Exception e) {
            if (e.getCause().toString().contains("UNIQUE_ERPMU_Name")) {
                message = "Sorry, the User Id '" + erpmusers.getErpmuName() + "' is not available. Please try with a differenet one";
            } else {
                message = "Exception in Save method -> RegisterUserAxn" + e.getMessage() + "Reported Cause is: " + e.getCause();
            }
            return ERROR;
        }
    }

    public String Edit() throws Exception {
        try {

            return SUCCESS;
        } catch (Exception e) {
            message = "Exception in Edit method -> RegisterUserAxn" + e.getMessage() + " Reported Cause is: " + e.getCause();
            return ERROR;
        }
    }

    public String DeleteUserProfile() throws Exception {
        try {
            
            ErpmuserroleDAO erpmurDao = new ErpmuserroleDAO();
            erpmur = erpmurDao.findByErpmUserRole(geterpmurId());
            erpmuName = erpmur.getErpmusers().getErpmuName();
            erpmurDao.delete(erpmur);
            imIdList = imDao.findAll();
            return SUCCESS;
        } catch (Exception e) {
            message = "Exception in Delete method -> DeleteUserProfileAxn " + e.getMessage() + " Reported Cause is: " + e.getCause();
            return ERROR;
        }
    }

    public String SaveUserProfile() throws Exception {
        try {           
            erpmusers = erpmusersDao.findByUserName(geterpmuName());
            erpmur.setErpmusers(erpmusers);
            erpmur.setErpmurActive('Y');
            ErpmuserroleDAO erpmurDao = new ErpmuserroleDAO();
            erpmurDao.save(erpmur);
            //Prepare Lists for Setting up User Profile
            imIdList = imDao.findAll();
           erpmurList = erpmurDao.findByErpmUserId(erpmusers.getErpmuId());  
            return SUCCESS;
        } catch (Exception e) {
            if (e.getCause().toString().contains("UNIQUE_ERPMU_ID_ERPMUR_DM_ID_ERMUR_IUR_ID"))
                message = "This profile is already assigned to you";
            else
                message = "Exception in ManageUserAxn method -> SaveUserProfile " + e.getMessage() + " Reported Cause is: " + e.getCause();
            return ERROR;
        }
    }


        public String ShowUserProfile() throws Exception {
        try {
            ErpmuserroleDAO erpmurDao = new ErpmuserroleDAO();
            erpmurList = erpmurDao.findActiveRolesByErpmUserId(Integer.parseInt(getSession().getAttribute("userid").toString()));
            erpmuName = erpmurList.get(0).getErpmusers().getErpmuFullName() + "(" +erpmurList.get(0).getErpmusers().getErpmuName() + ")";
            return SUCCESS;
        } catch (Exception e) {
            if (e.getCause().toString().contains("UNIQUE_ERPMU_ID_ERPMUR_DM_ID_ERMUR_IUR_ID"))
                message = "This profile is already assigned to you";
            else
                message = "Exception in ManageUserAxn method -> SaveUserProfile " + e.getMessage() + " Reported Cause is: " + e.getCause();
            return ERROR;
        }
    }

        public String ChooseUserProfile() throws Exception {
        try {
            ErpmuserroleDAO erpmurDao = new ErpmuserroleDAO();
            erpmur = erpmurDao.findByErpmUserRole(geterpmurId());

            getSession().setAttribute("imId", erpmur.getInstitutionmaster().getImId());
            getSession().setAttribute("imshortname", erpmur.getInstitutionmaster().getImShortName());
            getSession().setAttribute("simshortname",erpmur.getSubinstitutionmaster().getSimShortName());
            getSession().setAttribute("dmshortname", erpmur.getDepartmentmaster().getDmShortName());
           return SUCCESS;
        } catch (Exception e) {
            message = "Exception in ManageUserAxn method -> ChooseUserProfile " + e.getMessage() + " Reported Cause is: " + e.getCause();
            return ERROR;
        }
    }


    public String SetDefaultProfile() throws Exception {
        try {

            ErpmuserroleDAO erpmurDao = new ErpmuserroleDAO();
            erpmur = erpmurDao.findByErpmUserRole(geterpmurId());
            erpmur.setErpmurDefault('Y');
            erpmurDao.ClearDefaultProfile(erpmur.getErpmusers().getErpmuId());
            erpmurDao.update(erpmur);

            getSession().setAttribute("imId", erpmur.getInstitutionmaster().getImId());
            getSession().setAttribute("imshortname", erpmur.getInstitutionmaster().getImShortName());
            getSession().setAttribute("simshortname",erpmur.getSubinstitutionmaster().getSimShortName());
            getSession().setAttribute("dmshortname", erpmur.getDepartmentmaster().getDmShortName());

            erpmurList = erpmurDao.findAllInactiveUsers();
            return SUCCESS;
        } catch (Exception e) {
            message = "Exception in Delete method -> DeleteUserProfileAxn " + e.getMessage() + " Reported Cause is: " + e.getCause();
            return ERROR;
        }
    }

    public String AuthorizeUsers() throws Exception {
        try{
            ErpmuserroleDAO erpmurDao = new ErpmuserroleDAO();
            erpmurList = erpmurDao.findAllInactiveUsers();
        return SUCCESS;
        }
        catch (Exception e) {
            message = "Exception in ManageUserAxn method -> AuthorizeUsers " + e.getMessage() + " Reported Cause is: " + e.getCause();
            return ERROR;
        }
    }

    public String ApproveUserProfile() throws Exception {
        try {

            ErpmuserroleDAO erpmurDao = new ErpmuserroleDAO();
            erpmur = erpmurDao.findByErpmUserRole(geterpmurId());
            erpmur.setErpmurActive('Y');
            erpmurDao.update(erpmur);
            erpmurList = erpmurDao.findAllInactiveUsers();
            return SUCCESS;
        } catch (Exception e) {
            message = "Exception in Delete method -> DeleteUserProfileAxn " + e.getMessage() + " Reported Cause is: " + e.getCause();
            return ERROR;
        }
    }

    // Method to recover the Password


public String RecoverPassword() throws Exception {

    try {
           //Check if user has filled in all required values
            if (erpmusers.getErpmuSecretQuestion().contains("Invalid user name or date of birth") ||
                erpmusers.getErpmuSecretQuestion().contains("Please provide values for the above fields")) {
                message = "Please provide correct values for user name and date of birth";
                return INPUT;
            }
            else
            {
                erpmusersDao = new ErpmusersDAO();
                Erpmusers erpmu = erpmusersDao.FindByUserNameSecretAnswer(erpmusers.getErpmuName(), erpmusers.getErpmuSecretAnswer());
                if (erpmu == null) {
                    message = "Incorrect Answer. Try again";
                    erpmusers = null;
                    return INPUT;
                }                    
                else
                {
                Locale locale = ActionContext.getContext().getLocale();
                ResourceBundle bundle = ResourceBundle.getBundle("pico", locale);
                if(!bundle.getString("emailFrom").equals("") && !bundle.getString("emailUser").equals("") && !bundle.getString("emailFromPasswd").equals("")) {
                    String toEmailAddress = erpmu.getErpmuName();
                    String emailSubject = "Password for PICO Module";
                    String emailMessage = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/><title>Your Password Details</title></head><body><table width='500' border='0' align='center' cellpadding='15' cellspacing='0' style='font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12pt; color:#5a5a5a;'><tr><td align='left'><p>Dear " + erpmu.getErpmuFullName() + ",</p></td></tr><tr><td align='left'><p>Your password is:</p><br/><br/><p>Password: " + erpmu.getErpmuPassword() + "<br /></p><br/><p>Thank you for using this site.<br /></p><br/><br/><p>Regards,<br />Administrator, PICO Module<br /></p><p><br /><br />THIS IS AN AUTOMATED MESSAGE; PLEASE DO NOT REPLY. </p></td></tr></table></body></html>";
                    sendMail.sendMail(bundle.getString("emailFrom"), bundle.getString("emailUser"), bundle.getString("emailFromPasswd"), toEmailAddress, emailSubject, emailMessage);
                    message = "An email containing your password has been sent to you";
                }
                return SUCCESS;
                }
            }
        }
        catch (Exception e) {
            if (e.getCause().toString().contains("UnknownHostException"))
                message = "Unable to contact Mail Server. Please check your Internet connectivity and try again.";
            else
                message = "Exception in RecoverPassword method -> ManageUserAxn " + e.getMessage() + " Reported Cause is: " + e.getCause();
            return ERROR;
        }
    }

    public void validate() {

        try {
            //Validations on Address part
            if (erpmusers.getErpmuName() == null) {
                addFieldError("erpmuName", "Please enter user name");
            }
            if (geterpmusersdob().length() == 0)
                addFieldError("erpmusers.erpmusersdob", "Please enter your date of birth");
        } catch (NullPointerException npe) {
        }
    }


}
